package com.handydata.antifraud.service.impl;

import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.handydata.antifraud.bo.alarminfo.AlarmInfoBeanBO;
import com.handydata.antifraud.bo.alarminfo.AlarmInfoReqBO;
import com.handydata.antifraud.bo.alarminfo.AlarmInfoResBO;
import com.handydata.antifraud.common.constant.AlarmInfoCode;
import com.handydata.antifraud.common.exception.AlarmInfoExCode;
import com.handydata.antifraud.dao.AlarmInfoDao;
import com.handydata.antifraud.entity.AlarmInfoDO;
import com.handydata.antifraud.service.AlarmInfoService;
import com.handydata.antifraud.util.HttpUtil;
import com.handydata.antifraud.util.MailUtil;
import com.handydata.common.convert.CommonBeanConvertor;
import com.handydata.common.exception.SysException;
import com.handydata.common.service.AbsService;
import com.handydata.common.util.RedisUtil;

@Service("alarmInfoService")
public class AlarmInfoServiceImpl extends AbsService implements AlarmInfoService {
	
	private static final Logger logger = LoggerFactory.getLogger(AlarmInfoServiceImpl.class);
	
	@Autowired
	private AlarmInfoDao alarmInfoDao;
	@Autowired
	RedisUtil redisUtil;
	@Autowired
	MailUtil mailUtil;
//	private LinkedBlockingDeque linkedBlockingDeque;

	@Value("${urule.resporityServerUrl}")
	private  String resporityServerUrl;

	@Transactional
	@Override
	public AlarmInfoResBO createAlarmInfo(AlarmInfoReqBO req) throws SysException{


	    AlarmInfoResBO res = new AlarmInfoResBO();
		try {
			AlarmInfoDO entity = CommonBeanConvertor.convert(req, AlarmInfoDO.class);
			entity.setId(UUID.randomUUID().toString().replace("-", ""));
			entity.setCreateTime(Calendar.getInstance().getTime());
			long status = alarmInfoDao.insert(entity);
			if(status == 0) {
				res.setExCode(AlarmInfoExCode.SYS_NO_ENTITY_CREATED);
			} else {
				res.setExCode(AlarmInfoExCode.SUCCESS);
			}
		} catch (Exception e) {
			logger.error("Create new entity {} get into error", req, e);
			throw new SysException(AlarmInfoExCode.SYS_CREATE_ENTITY_ERROR);
		}
		return res;
	}

	@Transactional
	@Override
	public AlarmInfoResBO modifyAlarmInfo(AlarmInfoReqBO req) throws SysException{
	    AlarmInfoResBO res = new AlarmInfoResBO();
		try {
			AlarmInfoDO condition = CommonBeanConvertor.convert(req, AlarmInfoDO.class);
			long status = alarmInfoDao.update(condition);
			if(status == 0) {
				res.setExCode(AlarmInfoExCode.SYS_NO_ENTITY_MODIFIED);
			} else {
				res.setExCode(AlarmInfoExCode.SUCCESS);
			}
		} catch (Exception e) {
			logger.error("Modify entity {} get into error", req, e);
			throw new SysException(AlarmInfoExCode.SYS_MODIFY_ENTITY_ERROR);
		} 
		return res;
	}

	@Transactional
	@Override
	public AlarmInfoResBO deleteAlarmInfo(AlarmInfoReqBO req) throws SysException{
	    AlarmInfoResBO res = new AlarmInfoResBO();
		try {
			AlarmInfoDO condition = CommonBeanConvertor.convert(req, AlarmInfoDO.class);
			long status = alarmInfoDao.delete(condition);
			if(status == 0) {
				res.setExCode(AlarmInfoExCode.SYS_NO_ENTITY_DELETED);
			} else {
				res.setExCode(AlarmInfoExCode.SUCCESS);
			}
		} catch (Exception e) {
			logger.error("Delete entity {} get into error", req, e);
			throw new SysException(AlarmInfoExCode.SYS_DELETE_ENTITY_ERROR);
		}
		return res;
	}

	@Override
	public AlarmInfoResBO queryAlarmInfo(AlarmInfoReqBO req) throws SysException{
		AlarmInfoDO condition = CommonBeanConvertor.convert(req, AlarmInfoDO.class);
		AlarmInfoResBO res;
		try {
			int start=(req.getPageNumber()-1)*req.getPageSize();

			List<AlarmInfoDO> entities = alarmInfoDao.query(condition,start,start+req.getPageSize());
			res = CommonBeanConvertor.convert(entities, AlarmInfoResBO.class, AlarmInfoBeanBO.class);
			long count=alarmInfoDao.count(condition);
			res.setTotalNumber(count);
			double c1=count;
			double c2=req.getPageSize();

			res.setTotalPage(Double.valueOf(Math.ceil(c1/c2)).intValue());

			if(res.getEarlyWarnRecordList()!=null&&res.getEarlyWarnRecordList().size()>0){
				res.getEarlyWarnRecordList().stream().map((x) -> {
					//x.setSendModeName(AlarmConst.sendModelMap.get(x.gets()));
					//x.setAlertTypeName(AlarmConst.alertTypeMap.get(x.getAlertType()));
					//x.setAlertItemName(AlarmConst.alertItemMap.get(x.getAlertItem()));
					//x.setProductName(dictMap.get(x.getProductCode()));
					return x;
				});
			}
			res.setExCode(AlarmInfoExCode.SUCCESS);
		} catch(Exception e) {
			logger.error("Query entity {} get into error", req, e);
			throw new SysException(AlarmInfoExCode.SYS_QUERY_ENTITY_ERROR);
		}
		return res;
	}


		public void startWatchTimeOut(String alarmItem,String orderId,String code){

			try {

				String key=AlarmInfoCode.REDIS_ALARM_RULE_TIMEOUT.getCode()+"_"+alarmItem;

			     if(code!=null&&code.length()>0){
					 key+="_"+code;
				 }else {
			     	code="";
				 }

				Object obj= redisUtil.get(key);
				if(obj!=null){

					redisUtil.set(AlarmInfoCode.REDIS_ALARM_WACTH.getCode()+"_"+alarmItem+"_"+orderId+"_"+code,1,(Integer)obj);
				}else{
					//logger.error("没获取到超时时间 {} get into error", key);

					//throw new SysException(AlarmInfoExCode.SYS_NO_WATCH_TIME_ERROR);
				}
			} catch(Exception e) {
				logger.error("startWatchTimeOut {} get into error", alarmItem+"_"+code, e);
				//throw new SysException(AlarmInfoExCode.SYS_START_WATCH_ERROR);
			}
		}

		public void sendWatchAbNormal(String alarmItem,String orderId,String code,String alertType,String msg,Exception ex){//发到后管，通过后管发出去

			if(code==null) code="";
			String exinfo="";

			String key=alarmItem+"_"+orderId+"_"+code+"_"+alertType+"_"+msg+" ";
			if(ex!=null){
				StackTraceElement[] stackTraceElements=ex.getStackTrace();
				exinfo+=stackTraceElements[0].getClassName()+" "+stackTraceElements[0].getLineNumber()+" ";
				exinfo+=stackTraceElements[1].getClassName()+" "+stackTraceElements[1].getLineNumber()+"   ";
				exinfo+=stackTraceElements[2].getClassName()+" "+stackTraceElements[2].getLineNumber();
				exinfo=ex.getClass().getName()+ex.getMessage()+exinfo;
				key+=":"+exinfo;
			}

			try {
//				if(linkedBlockingDeque.size()>=300){
//					logger.error("错误队列已满，开始丢弃错误信息{}",key);
//					return;
//				}
//				linkedBlockingDeque.add(key);

				HttpUtil.sendDataByPost(resporityServerUrl+"/urule/sendmessage","key="+key,10000,null);

			}catch (Exception ex1){
				logger.error("发送错误消息到队列出错{}",key,ex1);
			}
		}


}
